# -*- coding: utf-8 -*-
import os
from smtplib import SMTP
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication


class Mailer(object):
    def __init__(self, host=None, port=None,
                 user=None, password=None,
                 subject=None, recipients=None):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.subject = subject
        self.recipients = recipients
        self.sevr = SMTP(self.host, self.port)
        self.sevr.ehlo()
        self.sevr.starttls()  # exchange special
        self.sevr.login(self.user, self.password)

    def __del__(self):
        if self.sevr:
            self.sevr.quit()

    def send(self, text, subject=None, recipients=None, file_list=None):
        assert isinstance(text, str)

        if subject is None:
            if self.subject:
                subject = self.subject
            else:
                raise Exception('subject: cannot be None.')
        if recipients is None:
            if self.recipients:
                recipients = self.recipients
            else:
                raise Exception('recipients: cannot be None.')
        msg = MIMEMultipart()
        msg['from'] = self.user
        msg['to'] = ','.join(self.recipients)
        msg['subject'] = Header(subject)
        if text:
            text_apart = MIMEText(text, _subtype='html', _charset='utf-8')
            msg.attach(text_apart)
        if file_list:
            for file_name in file_list:
                xlsx_apart = MIMEApplication(open(file_name, 'rb').read())
                name = os.path.split(file_name)[-1]
                xlsx_apart.add_header('Content-Disposition','attachment',filename = '%s' % name)
                msg.attach(xlsx_apart)

        self.sevr.sendmail(self.user, recipients, msg.as_string())

